Completed
Push — master ( 229673...de5280 )
by Dimas
08:59
created

roles.js ➔ initializeSelect2   F

Complexity

Conditions 15

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 20
rs 2.9998
c 0
b 0
f 0
cc 15

How to fix   Complexity   

Complexity

Complex classes like roles.js ➔ initializeSelect2 often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
function deleteRole(role) {
2
  console.log(getFuncName(), role);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
3
}
4
AjaxForm();
5
/**
6
 * Initialize global data source
7
 */
8
var dataSource = [];
9
var clonedCol = null;
10
11
jQuery(document).ready(function () {
12
  load_module(["select2"], function () {
13
    loadCSS("/assets/css/select2.min.css", function () {
14
      $.ajax({
15
        url: "",
16
        method: "post",
17
        data: {
18
          getAccess: guid(),
19
        },
20
        success: function (selectOptions) {
21
          if (selectOptions && Array.isArray(selectOptions)) {
22
            selectOptions.forEach(function (data, index) {
23
              dataSource.push({ text: data, id: data });
24
            });
25
          }
26
          //console.log(dataSource);
27
          initializeSelect2();
28
        },
29
      });
30
    });
31
  });
32
33
  $('[id^="add-select-"]').click(function (e) {
34
    e.preventDefault();
35
  });
36
37
  jQuery(document).on(
38
    "change",
39
    'select[id^="Roles-"],select[id^="Access-"]',
40
    buildData
41
  );
42
43
  // add new form access
44
  jQuery("#addAccess").click(function (e) {
45
    e.preventDefault();
46
    uinitializeSelect2();
47
    var first = jQuery('div[id^="Roles-"]');
48
    if (first.length) {
49
      var clone = first[0].cloneNode(true);
50
      clone.setAttribute("id", uniqid("Roles-"));
51
      $(clone)
52
        .find("select, button")
53
        .each(function () {
54
          $(this).attr("id", uniqid("Roles-"));
55
          if ($(this).attr("value")) {
56
            $(this).val("");
57
          }
58
        });
59
      //console.log(clone);
60
      $("#access-wrapper")[0].appendChild(clone);
61
    }
62
63
    initializeSelect2();
64
  });
65
});
66
67
function initializeSelect2() {
68
  jQuery('[id^="select-"],select.select2').each(function (index, value) {
69
    var t = jQuery(this);
70
    if (t.data("select2")) {
71
      console.error("select2 already initialized on " + t.attr("id"));
72
      return;
73
    }
74
    t.select2({
75
      data: dataSource.filter(onlyUnique),
76
      theme: "material",
77
      placeholder: "Select a route",
78
      allowClear: true,
79
    });
80
    var val = jQuery(this).data("key");
81
    if (val && val.length) {
82
      t.val(val).trigger("change");
83
    }
84
    //console.log(val);
85
  });
86
}
87
88
function uinitializeSelect2() {
89
  jQuery('[id^="select-"],select.select2').each(function (index, value) {
90
    var t = jQuery(this);
91
    if (t.data("select2")) t.select2("destroy");
92
  });
93
}
94
95
function buildData(e) {
96
  var wrapselgrab = $("form#access-management").find("div[id^=Roles-]");
97
  if (wrapselgrab.length) {
98
    wrapselgrab.each(function (index, el) {
99
      var selgrab = $(this).find("select");
100
      if (selgrab.length) {
101
        for (let index = 1; index < selgrab.length; index++) {
102
          var element = selgrab[index];
103
          element.setAttribute("name", `access[${selgrab[0].value}][]`);
104
          //console.log(selgrab[index].getAttribute("name"));
105
        }
106
      }
107
    });
108
  }
109
}
110
111
/**
112
 * Get unique array
113
 * @param {any} value
114
 * @param {any} index
115
 * @param {any[]} self
116
 * @example dataArray.filter(onlyUnique)
117
 */
118
function onlyUnique(value, index, self) {
119
  return self.indexOf(value) === index;
120
}
121